﻿using Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using Utility.Helper;

namespace BLL
{
    public class Lc_ConditionBLL : BaseBLL
    {
        public Lc_ConditionBLL()
        {
        }

        public Lc_ConditionBLL(Service service)
        {
            this.Service = service;
        }

        public DataTable GetAllInfo(string Style, object param)
        {
            string sql = string.Format(@"SELECT
    lcc.N_PROCESS_ID,
    lcp.C_PROCESS_NAME
FROM
    THKQS.Lc_Condition lcc,
    THKQS.Sys_User sysu,
    THKQS.Lc_Process lcp
WHERE
    lcc.N_CONDITION_OPERATOR_ID = sysu.USER_ID
    AND lcc.N_PROCESS_ID = lcp.N_PROCESS_ID");
            if (Style == "Condition")
            {
                string strC = param.ToString();
                string[] strs = strC.Split(',');
                if (strs[0] != "-1")
                {
                    sql += " AND lcc.N_PROCESS_ID='" + strs[0] + "'";
                }
                if (strs[1] != "-1")
                {
                    sql += "  AND lcc.N_CONDITION_STATE='" + strs[1] + "'";
                }
            }
            sql += " GROUP BY lcc.N_PROCESS_ID,lcp.C_PROCESS_NAME";

            DataTable dt = base.Query(sql, "", "", "", "");
            return dt;
        }

        /// <summary>
        /// 通过ID获取流程条件信息
        /// </summary>
        /// <param name="id">条件ID</param>
        /// <returns></returns>
        public Lc_Condition GetInfoById(string id)
        {
            string sql = string.Format(@"SELECT
	*
FROM
	LC_CONDITION
WHERE
	N_CONDITION_ID = {0}", id);
            DataTable dt = base.Query(sql, "", "", "", "");
            Lc_Condition model = new Lc_Condition();

            if (dt != null && dt.Rows.Count > 0)
            {
                model.N_CONDITION_ID = decimal.Parse(dt.Rows[0]["N_CONDITION_ID"].ToString());
                model.C_CONDITION_NAME = dt.Rows[0]["C_CONDITION_NAME"].ToString();
                model.N_PROCESS_ID = decimal.Parse(dt.Rows[0]["N_PROCESS_ID"].ToString());
                model.N_QUEUE_ID_LEFT = decimal.Parse(dt.Rows[0]["N_QUEUE_ID_LEFT"].ToString());
                model.N_QUEUE_ID_RIGHT = decimal.Parse(dt.Rows[0]["N_QUEUE_ID_RIGHT"].ToString());
                model.N_CONDITION_STATE = decimal.Parse(dt.Rows[0]["N_CONDITION_STATE"].ToString());
                model.N_CONDITION_OPERATOR_ID = decimal.Parse(dt.Rows[0]["N_CONDITION_OPERATOR_ID"].ToString());
                model.D_CONDITION_OPERATOR_TIME = DateTime.Parse(dt.Rows[0]["D_CONDITION_OPERATOR_TIME"].ToString());
                model.ISCONCURRENCY = decimal.Parse(dt.Rows[0]["ISCONCURRENCY"].ToString());
            }
            return model;
        }

        public bool Insert(Lc_Condition model, string operName)
        {
            model.N_CONDITION_ID = GetSequence("N_CONDITION_ID");
            var sql = string.Format(@"INSERT INTO LC_CONDITION(N_CONDITION_ID,
	C_CONDITION_NAME,
	N_PROCESS_ID,
	N_QUEUE_ID_LEFT,
	N_QUEUE_ID_RIGHT,
	N_CONDITION_STATE,
	N_CONDITION_OPERATOR_ID,
	D_CONDITION_OPERATOR_TIME,
	ISCONCURRENCY)
VALUES({0},'{1}',{2},{3},{4},{5},{6},TO_DATE('{7}', 'YYYY-MM-DD HH24:MI:SS'),{8})",
                                                                                  model.N_CONDITION_ID,
                                                                                  model.C_CONDITION_NAME,
                                                                                  model.N_PROCESS_ID,
                                                                                  model.N_QUEUE_ID_LEFT,
                                                                                  model.N_QUEUE_ID_RIGHT,
                                                                                  model.N_CONDITION_STATE,
                                                                                  model.N_CONDITION_OPERATOR_ID,
                                                                                  model.D_CONDITION_OPERATOR_TIME.ToString("yyyy-MM-dd HH:mm:ss"),
                                                                                  model.ISCONCURRENCY == null ? 0 : model.ISCONCURRENCY
                                                                                  );
            return base.NoQuery(sql, operName) > 0 ? true : false;
        }

        public bool Update(Lc_Condition model, string operName)
        {
            var sql = string.Format(@"UPDATE LC_CONDITION
SET
	C_CONDITION_NAME='{1}',
	N_PROCESS_ID={2},
	N_QUEUE_ID_LEFT={3},
	N_QUEUE_ID_RIGHT={4},
	N_CONDITION_STATE={5},
	N_CONDITION_OPERATOR_ID={6},
	D_CONDITION_OPERATOR_TIME=TO_DATE('{7}','YYYY-MM-DD HH24:MI:SS'),
	ISCONCURRENCY={8}
WHERE N_CONDITION_ID={0}",
                         model.N_CONDITION_ID,
                         model.C_CONDITION_NAME,
                         model.N_PROCESS_ID,
                         model.N_QUEUE_ID_LEFT,
                         model.N_QUEUE_ID_RIGHT,
                         model.N_CONDITION_STATE,
                         model.N_CONDITION_OPERATOR_ID,
                         model.D_CONDITION_OPERATOR_TIME.ToString("yyyy-MM-dd HH:mm:ss"),
                         model.ISCONCURRENCY);
            return base.NoQuery(sql, operName) > 0 ? true : false;
        }

        public int DELETE(string ids, string operName)
        {
            if (string.IsNullOrEmpty(ids))
            {
                return 1;
            }
            var sql = string.Format("DELETE FROM LC_CONDITION WHERE N_CONDITION_ID IN ({0})", ids);
            return base.NoQuery(sql, operName);
        }

        public int DELETE(decimal[] ids)
        {
            var arry = new List<int>();
            foreach (var item in ids)
            {
                arry.Add(Convert.ToInt32(item));
            }
            return DELETE(arry.ToIn(), User.USER_NAME);
        }

        public int GetRecordCount(string whereStr)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append(@"SELECT count(1) FROM
    Lc_Condition t,
    Lc_Process p,
    Sys_User u
WHERE
    t.N_PROCESS_ID = p.N_PROCESS_ID
    AND t.N_CONDITION_OPERATOR_ID = u.USER_ID ");
            if (!string.IsNullOrEmpty(whereStr))
            {
                strSql.Append(whereStr);
            }

            var dt = base.Query(strSql.ToString(), "", "", "", "");
            if (dt != null && dt.Rows.Count > 0)
            {
                return Convert.ToInt32(dt.Rows[0][0]);
            }
            else
            {
                throw new Exception("SQL查询异常,请检查SQL语法是否异常");
            }
        }

        public DataTable GetListByPage(string whereStr, string orderby, int Index, int count)
        {
            var sql = @"SELECT
                        t.N_CONDITION_ID,
                        t.C_CONDITION_NAME,
                        p.C_PROCESS_NAME,
                        t.N_QUEUE_ID_LEFT,
                        (SELECT C_NODE_NAME
                        FROM THKQS.Lc_Node
                        WHERE Lc_Node.N_NODE_ID =
                        (SELECT N_NODE_ID
                        FROM THKQS.Lc_Queue
                        WHERE N_QUEUE_ID = t.N_QUEUE_ID_LEFT)) leftName,
                        t.N_QUEUE_ID_RIGHT,
                        (SELECT C_NODE_NAME
                        FROM THKQS.Lc_Node
                        WHERE Lc_Node.N_NODE_ID =
                        (SELECT N_NODE_ID
                        FROM THKQS.Lc_Queue
                        WHERE N_QUEUE_ID = t.N_QUEUE_ID_RIGHT)) rightName,
                        CASE t.N_CONDITION_STATE
                        WHEN 0 THEN '停用'
                        WHEN 1 THEN '使用'
                        WHEN 2 THEN '开始'
                        WHEN 3 THEN '结束'
                        END as N_CONDITION_STATE,
                        u.USER_NAME,
                        to_char(t.D_CONDITION_OPERATOR_TIME,'yyyy-mm-dd HH24:MI:SS') D_CONDITION_OPERATOR_TIME
                    FROM
                        Lc_Condition t
                        LEFT JOIN Lc_Process p ON t.N_PROCESS_ID = p.N_PROCESS_ID
                        LEFT JOIN Sys_User u ON t.N_CONDITION_OPERATOR_ID = u.USER_ID
                    WHERE
                        1=1 {0}
                    ORDER BY t.{1}";
            sql = string.Format(sql, whereStr, orderby);
            return PageQuery(sql, (Index - 1) * count, count);
            /*
            StringBuilder strSql = new StringBuilder();

            strSql.Append(@"SELECT * FROM (SELECT  ROW_NUMBER() OVER(ORDER BY t." + orderby + @") as r,
    t.N_CONDITION_ID,
    t.C_CONDITION_NAME,
    p.C_PROCESS_NAME,
    t.N_QUEUE_ID_LEFT,
    (SELECT C_NODE_NAME
    FROM THKQS.Lc_Node
    WHERE Lc_Node.N_NODE_ID =
    (SELECT N_NODE_ID
    FROM THKQS.Lc_Queue
    WHERE N_QUEUE_ID = t.N_QUEUE_ID_LEFT)) leftName,
    t.N_QUEUE_ID_RIGHT,
    (SELECT C_NODE_NAME
    FROM THKQS.Lc_Node
    WHERE Lc_Node.N_NODE_ID =
    (SELECT N_NODE_ID
    FROM THKQS.Lc_Queue
    WHERE N_QUEUE_ID = t.N_QUEUE_ID_RIGHT)) rightName,
    CASE t.N_CONDITION_STATE
    WHEN 0 THEN '停用'
    WHEN 1 THEN '使用'
    WHEN 2 THEN '开始'
    WHEN 3 THEN '结束'
    END as N_CONDITION_STATE,
    u.USER_NAME,
    t.D_CONDITION_OPERATOR_TIME
FROM
    Lc_Condition t
    LEFT JOIN Lc_Process p ON t.N_PROCESS_ID = p.N_PROCESS_ID
    LEFT JOIN Sys_User u ON t.N_CONDITION_OPERATOR_ID = u.USER_ID
WHERE
    1=1 ");
            if (!string.IsNullOrEmpty(whereStr.Trim()))
            {
                strSql.Append(whereStr);
            }
            strSql.Append(@" ) TT");
            if (Index >= 2)
            {
                strSql.AppendFormat(" WHERE TT.r BETWEEN ({0}-1)*{1}+1 AND {0}*{1}", Index, count);
            }
            else
            {
                strSql.AppendFormat(" WHERE TT.r BETWEEN ({0}-1)*{1} AND {0}*{1}", Index, count);
            }
            var sql=strSql.ToString();
            return base.Query(sql, "", "", "", "");
            */
        }

        /// <summary>
        /// 转交条件
        /// </summary>
        /// <param name="processId"></param>
        /// <param name="firstQueue"></param>
        /// <returns></returns>
        public DataTable GetCirculationConditon(string processId, string firstQueue, string win, string loname)
        {
            string sql = @"select t.n_condition_id id,t.c_condition_name name
  from lc_condition t
 where t.n_condition_state <> 0
   and t.n_process_id =" + processId + @"
   and t.n_queue_id_left= " + firstQueue + " order by  N_CONDITION_ID";

            DataTable dt = Query(sql, win, "GetCirculationConditon", loname, loname);
            return dt;
        }

        public DataTable GetCurrentNode(string trid)
        {
            string sql = @"
select n.N_NODE_ID                  节点编号,
       q.N_QUEUE_ID                 队列编号,
       q.N_QUEUE_NUMBER             队列序号,
       t.N_PROCESS_ID               流程编号,
       t.N_BUSINESS_ID              业务编号,
       n.c_node_name                节点名称,
       n.N_TRANSACTION_TIME         办理天数,
       t.D_TRANSACTION_TIME_BEGIN   开始时间,
       b.n_business_name            业务名称,
       b.n_business_operator_id     业务操作员,
       t.n_transaction_id           办理流水号,
       t.N_LAST_BACE_TRANSACTION_ID 上级流水,
       q.N_MUT_STATE                节点执行状态,
       q.N_MEETING                  汇合点,
       t.d_transaction_time_due     到期时间,
       q.N_AUDIT_TYPE               审核方式
  from lc_transaction t, lc_queue q, lc_node n, qs_business b
 where t.N_QUEUE_ID = q.N_QUEUE_ID
   and n.N_NODE_ID = q.N_NODE_ID
   and t.N_BUSINESS_ID = b.N_BUSINESS_ID
   and t.N_TRANSACTION_STATE = 0
   and t.n_transaction_id =" + trid;

            DataTable dt = Query(sql, "", "GetCurrentNode", "", "");
            return dt;
        }

        /// <summary>
        /// 获取下一个流程节点
        /// </summary>
        /// <param name="processId">流程编号</param>
        /// <param name="firstQueue"></param>
        /// <returns></returns>
        public DataTable GetNextNum(decimal processId, decimal firstQueue)
        {
            string nextNum = string.Empty;
            string sql = @"select c.n_queue_id_right 下一个队列,
       (select n.c_node_name from lc_node n where n.n_node_id = q.n_node_id) 节点名称,
       C.n_Condition_State 条件状态
  from lc_queue q, lc_condition c
 where c.n_queue_id_right = q.n_queue_id
   and c.n_condition_state <> 0
   and q.n_process_id =" + processId + @"
   and c.n_queue_id_left =" + firstQueue + " order by q.n_queue_number";

            DataTable dt = Query(sql, "", "GetNextNum", "", "");
            return dt;
        }
    }
}